package com.addplus.townmall.server.scheduled.scheduletask;

import com.addplus.townmall.server.api.mapper.town.*;
import com.addplus.townmall.server.api.model.town.*;
import com.addplus.townmall.server.api.utils.DataUtils;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 类名: UpdateIntegralZeroTask
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/11/8 2:57 PM
 * @description 类描述: 秒杀活动状态更改定时器
 */
@Component
public class UpdateIntegralZeroTask {

    private Logger logger = LoggerFactory.getLogger(UpdateIntegralZeroTask.class);

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    OrderItemsFightMapper orderItemsFightMapper;

    @Autowired
    TownOrderFightMapper townOrderFightMapper;
    @Autowired
    MemberIntegralMapper memberIntegralMapper;

    /**
     * 年底商城用户积分清零
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 59 23 31 12 *")
    private void updateIntegralZero() throws Exception {
        logger.info("年底商城用户积分清零任务开始");
        QueryWrapper<MemberIntegral> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("gmt_modified");
        List<MemberIntegral> memberIntegrals = memberIntegralMapper.selectList(queryWrapper);
        if (memberIntegrals == null || memberIntegrals.isEmpty()) {
            logger.info("积分清零，年底商城用户积分记录为空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            memberIntegrals.forEach(item -> {
                UpdateWrapper<MemberIntegral> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", item.getId());

                updateWrapper.set("integral_expired", item.getIntegralExpired() + item.getIntegralNow());
                updateWrapper.set("integral_now", 0);
                updateWrapper.set("gmt_modified", localDateTimeNow);
                memberIntegralMapper.update(new MemberIntegral(), updateWrapper);
            });
        }
        logger.info("年底商城用户积分清零任务完成");
    }

}
